package com.application.model.gobierno.caba.retrieve;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.application.model.exceptions.ItemNotFoundexception;
import com.application.model.gobierno.caba.entities.ManagerGobCabaColegio;

public class RetrieveGobCABAAviso extends RetrieveGobCABARegex {

	private RetrieveGobCABADetalle	retrieveGobCABADetalle;
	
    public RetrieveGobCABAAviso(ManagerGobCabaColegio	manager) {
    	super(manager);
    	retrieveGobCABADetalle = new RetrieveGobCABADetalle(manager);
    }

    @Override
    public void processContent(String data, String parentName) {
    	Pattern     pattern = null;
        Matcher     matcher = null;
        String      regex = null;
    	regex = "<tr(.*?)</tr>";
        pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL|Pattern.UNICODE_CASE|Pattern.UNIX_LINES);
        matcher = pattern.matcher(data);
        
        while (matcher.find()) {
        	try {
				procesarAvisos(matcher.group(1),parentName);
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
    }


	private void procesarAvisos(String data, String parentName) throws ItemNotFoundexception {
		Pattern     pattern = null;
        Matcher     matcher = null;
        String      regex = null;
        
        Boolean		encontrado = Boolean.FALSE;
        String 		gestion = "";
        String 		tipo = "";
        String 		linkDetalle = "";
        String 		nombre = "";
        String		direccion = "";
        String 		barrio = "";
        String		urlBasico = "";
        
        urlBasico = "http://www.buenosaires.edu.ar/areas/educacion/establecimientos/";
        regex = "<td align=\"center\">(.*?)</td><td>(.*?)</td><td class=\"titulo_fila\"><a href=\"(.*?)\">(.*?)</a>(.*?)<td width=\"95\" align=\"center\">(.*?)</td><td width=\"108\" align=\"center\">(.*?)</td>";
        pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL|Pattern.UNICODE_CASE|Pattern.UNIX_LINES);
        matcher = pattern.matcher(data);
        
        while (matcher.find()) {
        	
        	encontrado = Boolean.TRUE;
        	nombre = escapeValue(matcher.group(4));
        	if(!nombre.isEmpty()){
	        	gestion = matcher.group(1);
	        	tipo = matcher.group(2);
	        	linkDetalle = matcher.group(3);
	        	
	        	direccion = matcher.group(6);
	        	barrio = matcher.group(7);
	        	
	        	
	        	manager.agregarItem(nombre, gestion,direccion,barrio);
	        	generarTipo(nombre,tipo);
	        	retrieveGobCABADetalle.retrivie(urlBasico+linkDetalle, "detalle", "Ficha t", "Tabla de b","iso-8859-1");
        	}
        }
        if(!encontrado){
        	throw new ItemNotFoundexception("La busqueda no fue encontrada");
        }
	}


	
}
